package com.clh.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.clh.common.PageInfo;
import com.clh.dto.Result;
import com.clh.entity.Pay;
import com.clh.service.PayService;
import com.clh.service.impl.PayServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Servlet implementation class PayServlet
 */
@WebServlet("/PayServlet")
public class PayServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private PayService payService = new PayServiceImpl();

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String op = request.getParameter("op");
		if ("delete".equals(op)) {// 删除操作
			this.dodelete(request, response);
		} else if ("page".equals(op)) {
			this.doQueryByPage(request, response);
		} else if ("add".equals(op)) {
			this.doAddPay(request, response);
		} else if ("update".equals(op)) {
			this.doUpdate(request, response);
		} else if ("findById".equals(op)) {
			this.doFindByNo(request, response);
		} else if ("immediatelyPay".equals(op)) {
			this.doImmediatelyPay(request, response);
		} else if ("pageByWeiJiao".equals(op)) {
			this.doQueryByPageByWeiJiao(request, response);
		} else if ("generate".equals(op)) {// 生成各项费用
			String typeId = request.getParameter("typeId");
			if ("1".equals(typeId)) {// 生成物业费
				this.doGenerateProperties(request, response, typeId);
			} else if ("2".equals(typeId)) {// 生成水费
				this.doGenerateWater(request, response, typeId);
			} else if ("4".equals(typeId)) {// 生成电费
				this.doGenerateElectric(request, response, typeId);
			}
		} else if("payDone".equals(op)) {//支付完成，修改订单状态
			this.doPayDone(request,response);
		}
	}

	/* @Description:（方法功能描述）
	* @param request
	* @param response（展示方法参数和返回值）
	*/
	private void doPayDone(HttpServletRequest request, HttpServletResponse response) {
		// 统一的返回对象
		Result result = new Result();
		
		//获取前端传来的待修改订单编号
		String payNo=request.getParameter("payNo");
		if(payNo!=null) {
			//调用业务修改订单状态
			boolean flag = payService.updatePayStatus(payNo);
			if(flag) {
				result.ok(true).setMessage("汤臣二品提醒您：支付成功！");
			}else {
				result.fail(0, "订单状态修改失败，请联系物业");
			}
		}else {
			result.fail(0, "未传入订单号");
		}
		
		
	}

	private void doGenerateElectric(HttpServletRequest request, HttpServletResponse response, String typeId) throws IOException {
		// 统一的返回对象
		Result result = new Result();
		// 获取参数
		String	payYear = request.getParameter("payYear");
		String	payMonth = request.getParameter("payMonth");
		// 调用业务判断是否重复生成
		String repeatPay = payYear + (payMonth.length()>1?payMonth:"0"+payMonth) +typeId;
		boolean payExist = payService.isExist(repeatPay);
		if (payExist) {
			result.fail(0, "电费缴费订单已存在！请勿重复生成");
		} else {// 无此类订单，可生成
			boolean flag = payService.electricGenerate(payYear, payMonth);

			if (flag) {
				result.ok(true).setMessage("电费缴费订单生成成功");
			} else {
				result.fail(0, "电费缴费订单生成失败");
			}
		}
		// 响应
		response.setContentType("application/json;charset=utf-8");
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(result);
		response.getWriter().write(json);
		
	}

	private void doGenerateWater(HttpServletRequest request, HttpServletResponse response, String typeId) throws IOException {
		// 统一的返回对象
		Result result = new Result();
		// 获取参数
		String	payYear = request.getParameter("payYear");
		String	payMonth = request.getParameter("payMonth");
		// 调用业务判断是否重复生成
		String repeatPay = payYear + (payMonth.length()>1?payMonth:"0"+payMonth) +typeId;
		boolean payExist = payService.isExist(repeatPay);
		if (payExist) {
			result.fail(0, "水费缴费订单已存在！请勿重复生成");
		} else {// 无此类订单，可生成
			boolean flag = payService.waterGenerate(payYear, payMonth);

			if (flag) {
				result.ok(true).setMessage("水费缴费订单生成成功");
			} else {
				result.fail(0, "水费缴费订单生成失败");
			}
		}
		// 响应
		response.setContentType("application/json;charset=utf-8");
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(result);
		response.getWriter().write(json);
	}

	private void doGenerateProperties(HttpServletRequest request, HttpServletResponse response, String typeId)
			throws IOException {
		// 统一的返回对象
		Result result = new Result();

		// 获取参数
		String payYear = request.getParameter("payYear");
		String payMonth = request.getParameter("payMonth");
		// 调用业务判断是否重复生成
		String repeatPay = payYear + (payMonth.length()>1?payMonth:"0"+payMonth) +typeId;
		boolean payExist = payService.isExist(repeatPay);
		
		if (payExist) {
			result.fail(0, "物业费缴费订单已存在！请勿重复生成");
		} else {// 无此类订单，可生成
				// 生成物业费订单
			boolean Pflag = payService.propertyGenerate(payYear, payMonth);

			if (Pflag) {
				result.ok(true).setMessage("物业费缴费订单生成成功");
			} else {
				result.fail(0, "物业费缴费订单生成失败");
			}
		}

		// 响应
		response.setContentType("application/json;charset=utf-8");
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(result);
		response.getWriter().write(json);
	}

	/**
	 * @param request
	 * @param response
	 */

	/**
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doImmediatelyPay(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Result result = new Result();
		String payNo = request.getParameter("payNo");

		Pay pay = payService.getPayById(payNo);

		if (pay != null) {
			result.ok(pay);
		} else {
			result.fail(0, "请求失败");
		}

		// 响应
		response.setContentType("application/json;charset=utf-8");
		// 利用第三方库jackson转换
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(result);
		// 创建响应并将数据返回给浏览器
		response.getWriter().write(json);

	}

	/**
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doFindByNo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println("进来了");
		// 统一的响应对象格式
		Result result = new Result();
		// 接受请求参数
		String payNo = request.getParameter("payNo");

		// 校验参数
		if (payNo == null || "".equals(payNo.trim())) {
			System.out.println("空的");
			result.fail(0, "参数错误");
		} else {
			// 调用业务层
			Pay pay = payService.getPayById(payNo);
			if (pay != null) {
				result.ok(pay);
			} else {
				result.fail(0, "没有相关数据");
			}
		}
		// 响应
		response.setContentType("application/json;charset=utf-8");
		// 利用第三方库jackson转换
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(result);
		// 创建响应并将数据返回给浏览器
		response.getWriter().write(json);

	}

	/**
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doUpdate(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 统一的响应对象格式
		Result result = new Result();
		// 接受请求参数
		String payNo = request.getParameter("payNo");// 修改条件
		String roomNo = request.getParameter("roomNo");
		String payStartTime = request.getParameter("startTime");
		String payEndTime = request.getParameter("endTime");
		String payTypeId = request.getParameter("payTypeId");
		String payMoney = request.getParameter("payMoney");
		String payStatus = request.getParameter("payStatus");
		String payTime = request.getParameter("payTime");
		if ("暂未缴费".equals(payTime)) {
			payTime = null;
			payStatus = 0 + "";
			System.out.println(payStatus + "ddddddddddddddddddddddd");
		}

		Pay pay = new Pay();
		pay.setPayNo(payNo);
		pay.setRoomNo(roomNo);
		pay.setPayStartTime(payStartTime);
		pay.setPayEndTime(payEndTime);
		pay.setPayTypeId(Integer.valueOf(payTypeId));
		pay.setPayMoney(new BigDecimal(payMoney));
		pay.setPayTime(payTime);
		pay.setPayStatus(Integer.valueOf(payStatus));

		boolean f = payService.modifyPay(pay);
		if (f) {
			result.ok(f);
		} else {
			result.fail(0, "修改商品失败");
		}
		// 响应

		response.setContentType("application/json;charset=utf-8");
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(result);
		// 创建响应并将数据返回给浏览器
		response.getWriter().write(json);
	}

	/**
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doAddPay(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 统一的响应对象格式
		Result result = new Result();
		// 接受请求参数
		String roomNo = request.getParameter("roomNo");
		String payTypeId = request.getParameter("payTypeId");
		String payMoney = request.getParameter("payMoney");

		Pay pay = new Pay();
		pay.setRoomNo(roomNo);
		pay.setPayTypeId(Integer.valueOf(payTypeId));
		pay.setPayMoney(new BigDecimal(payMoney));
		pay.setPayStatus(0);

		boolean f = payService.addPay(pay);
		if (f) {
			result.ok(f);
		} else {
			result.fail(0, "新增缴费记录失败");
		}
		// 响应

		response.setContentType("application/json;charset=utf-8");
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(result);
		// 创建响应并将数据返回给浏览器
		response.getWriter().write(json);

	}

	private void doQueryByPageByWeiJiao(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 统一的响应对象格式
		Result result = new Result();
		// 接收请求参数
		String start = request.getParameter("start");
		String end = request.getParameter("end");
		String roomNo = request.getParameter("roomNo");
		String payType = request.getParameter("payType");

		String pageNum = request.getParameter("pageNum");
		String pageSize = request.getParameter("pageSize");
		System.out.println("roomNo" + roomNo + "payType" + payType);
		System.out.println("pageNum;" + pageNum + ",pageSize:" + pageSize);
		// 对请求参数进行校验
		if ((pageNum == null || "".equals(pageNum) || Integer.parseInt(pageNum) < 0)
				|| (pageSize == null || "".equals(pageSize) || Integer.parseInt(pageSize) < 0)) {
			result.fail(0, "参数错误");
		} else {
			// 调用业务层
			Pay pay = new Pay();
			pay.setRoomNo(roomNo);
			if (payType != null && !"".equals(payType)) {
				pay.setPayTypeId(Integer.valueOf(payType));
			}

			PageInfo pageInfo = payService.getPayListByPageInNOAndType(start, end, payType, roomNo,
					Integer.valueOf(pageNum), Integer.valueOf(pageSize));
			if (!pageInfo.getList().isEmpty()) {
				result.ok(pageInfo);
			} else {
				result.fail(0, "没有相关数据");
			}
		}
		// 设置响应的内容类型
		response.setContentType("application/json;charset=utf-8");
		// 利用第三方库jackson转换
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(result);
		// 创建响应并将数据返回给浏览器
		response.getWriter().write(json);
	}

	/**
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doQueryByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 统一的响应对象格式
		Result result = new Result();
		// 接收请求参数
		String start = request.getParameter("start");
		String end = request.getParameter("end");
		String roomNo = request.getParameter("roomNo");
		System.out.println("dasdasd" + roomNo);
		String pageNum = request.getParameter("pageNum");
		String pageSize = request.getParameter("pageSize");

		System.out.println("pageNum;" + pageNum + ",pageSize:" + pageSize);
		// 对请求参数进行校验
		if ((pageNum == null || "".equals(pageNum) || Integer.parseInt(pageNum) < 0)
				|| (pageSize == null || "".equals(pageSize) || Integer.parseInt(pageSize) < 0)) {
			result.fail(0, "参数错误");
		} else {
			// 调用业务层
			Pay pay = new Pay();
			pay.setRoomNo(roomNo);
			PageInfo pageInfo = payService.getPayListByPage(start, end, roomNo, Integer.parseInt(pageNum),
					Integer.parseInt(pageSize));
			if (!pageInfo.getList().isEmpty()) {
				result.ok(pageInfo);
			} else {
				result.fail(0, "没有相关数据");
			}
		}
		// 设置响应的内容类型
		response.setContentType("application/json;charset=utf-8");
		// 利用第三方库jackson转换
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(result);
		// 创建响应并将数据返回给浏览器
		response.getWriter().write(json);
	}

	/**
	 * @param request
	 * @param response
	 */
	private void dodelete(HttpServletRequest request, HttpServletResponse response) {
		// 统一的响应对象格式
		Result result = new Result();
		try {
			String payNo = request.getParameter("payNo");
			if (payNo == null || "".equals(payNo)) {
				result.fail(400, "参数错误");
			} else {
				int n = payService.deleteByPayNo(payNo);
				if (n > 0) {
					result.ok(true).setMessage("删除成功");
				} else {
					result.fail(0, "删除失败，可能原因是它不存在，或者被关联引用！");
				}
			}
//			// 设置相应的内容类型
			response.setContentType("application/json;charset=utf-8");
			// 利用第三方库jackson转换
			ObjectMapper objectMapper = new ObjectMapper();
			String json = objectMapper.writeValueAsString(result);
			// 创建响应并将数据返回给浏览器
			response.getWriter().write(json);

		} catch (Exception e) {
			result.fail(500, "服务器出错了");
		}

	}

}
